import * as R from 'ramda';

import { Button, Modal, Popconfirm, Space, Table, Tooltip } from 'antd';
import { ButtonEnum, menuTypeOptions } from '../../../../lib/enums';
import React, {
  Fragment,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from 'react';
import {
  appendEllipsis,
  calcProTableScrollHeight,
  optionsToValueEnum,
  unResWrapper,
} from '../../../../utils/common';
import {
  createMenu,
  deleteMenu,
  getMenuDetail,
  getMenuTree,
  updateMenu,
} from '../../../../service/menu';

import AuthButton from '../../../../containers/AuthButton';
import ConfirmButton from '../../../../components/ConfirmButton';
import EnumTag from '../../../../components/EnumTag';
import Icon from '../../../../components/Icon';
import MenuForm from '../components/MenuForm';
import ProTable from '@ant-design/pro-table';
import ToCode from '../components/ToCode';
import { useButtonPermission } from '../../../../hooks/permissions';
import useCRUD from '../../../../hooks/useCRUD';
import { useFloatLayer } from '@r-magician/hooks';

const MenuList = ({ curSystem }) => {
  const systemId = useMemo(() => curSystem.id, [curSystem]);

  const {
    isEdit,
    form,
    openHandle,
    dataSource,
    fetchList,
    visible,
    confirmLoading,
    okHandle,
    close,
    removeHandle,
    removeLoading,

    actionRef,
  } = useCRUD({
    createService: (data) => createMenu({ systemId, ...data }),
    updateService: unResWrapper(({ id, ...data }) =>
      updateMenu(id, { ...data }),
    ),
    listService: unResWrapper((data) => getMenuTree({ systemId, ...data })),
    getService: unResWrapper(R.compose(getMenuDetail, R.prop('id'))),
    deleteService: unResWrapper(deleteMenu),
    refreshDeps: [systemId],
    messages: {
      create: '创建菜单成功',
      update: '更新菜单成功',
      remove: '删除菜单成功',
    },
  });
  const { hasRemoveMenuAuthority } = useButtonPermission();
  const columns = [
    { title: '菜单名称', dataIndex: 'name' },
    { title: '菜单编码', dataIndex: 'code', copyable: true },
    {
      title: '菜单类型',
      dataIndex: 'type',
      valueType: 'select',
      valueEnum: optionsToValueEnum(menuTypeOptions.getOptions()),
      render: (_, { type }) => {
        return <EnumTag.MenuTag value={type} />;
      },
    },
    {
      title: '菜单ICON',
      dataIndex: 'icon',
      width: 200,
      search: false,
      render: (v) => {
        return (
          <Tooltip title={v}>
            <Icon type={v} style={{ fontSize: 20 }} />
          </Tooltip>
        );
      },
    },
    {
      title: '菜单链接',
      dataIndex: 'url',
      width: 200,
      copyable: true,
      search: false,
    },
    { title: '排序', dataIndex: 'sort', search: false },
    {
      title: '操作',
      search: false,
      width: 200,
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            <AuthButton
              code={ButtonEnum.UPDATE_MENU}
              size="small"
              type="link"
              onClick={() => openHandle(row)}
            >
              编辑
            </AuthButton>
            {hasRemoveMenuAuthority && (
              <ConfirmButton
                confirmProps={{
                  title: `确定删除菜单【${row.name}】?`,
                }}
                text="删除"
                service={() => removeHandle(row)}
                buttonProps={{ size: 'small', danger: true, type: 'text' }}
              />
            )}
          </Space>
        );
      },
    },
  ];

  const [selectMenuList, setSelectMenuList] = useState([]);
  const toCodeFl = useFloatLayer({
    onClose() {
      setSelectMenuList([]);
    },
  });
  const openToCode = useCallback(
    (data) => {
      setSelectMenuList(data);
      toCodeFl.open();
    },
    [toCodeFl],
  );
  return (
    <Fragment>
      <Modal
        visible={visible}
        width="70%"
        onOk={okHandle}
        confirmLoading={confirmLoading}
        onCancel={close}
        title="创建菜单"
        destroyOnClose
        okText="确认"
        cancelText="取消"
      >
        <MenuForm form={form} treeData={dataSource} editable={isEdit} />
      </Modal>
      <Modal
        title="枚举代码"
        destroyOnClose
        width="70%"
        visible={toCodeFl.visible}
        onCancel={toCodeFl.close}
        footer={null}
      >
        <ToCode data={selectMenuList} />
      </Modal>
      <ProTable
        size="small"
        rowSelection={{
          selections: [Table.SELECTION_ALL],
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>已选 {selectedRowKeys.length} 项</span>
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </Space>
        )}
        request={(data) => {
          return fetchList(data).then((res) => {
            return {
              data: res,
            };
          });
        }}
        options={{
          fullScreen: true,
        }}
        tableAlertOptionRender={({ selectedRows }) => {
          return (
            <Space size={16}>
              <Button type="primary" onClick={() => openToCode(selectedRows)}>
                生成JS编程枚举
              </Button>
            </Space>
          );
        }}
        scroll={{ y: 400, x: '120%' }}
        actionRef={actionRef}
        rowKey="id"
        columns={appendEllipsis(columns)}
        pagination={false}
        toolBarRender={() => [
          <AuthButton
            code={ButtonEnum.CREATE_MENU}
            key="create"
            type="primary"
            onClick={() => openHandle()}
          >
            创建菜单
          </AuthButton>,
        ]}
      />
    </Fragment>
  );
};

export default MenuList;
